package com.dx.weichat.weichat;

import com.dx.weichat.weichat.redisUtils.RedisUtil;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * @author: dx
 * @date: 2018/10/8/0008
 * @description: 初始化执行操作
 */
@Component
public class InitApplication implements CommandLineRunner {
	private static Logger logger = LoggerFactory.getLogger(InitApplication.class);
	@Autowired
	private RedisUtil redisUtil;
	@Value("classpath:_city.json")
	private Resource resource;
	@Override
	public void run(String... args) throws Exception {
		logger.info("***************************************执行初始化操作****************************");
		//先判断redis中是否存在城市的数据
		if(redisUtil.get("cityData")==null) {
			String areaData = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
			JSONArray jsonArray = new JSONArray(areaData);
			//存入redis
			for (Object obj : jsonArray) {
				JSONObject jsonObject = (JSONObject) obj;
				if (jsonObject.has("city_name")) {
					redisUtil.set(jsonObject.getString("city_name"), jsonObject.getString("city_code"));
				} else if (jsonObject.has("commandList")) {
					redisUtil.set("commandList", jsonObject.getString("commandList"));
				}else if (jsonObject.has("expireTime")){
					redisUtil.set("expireTime", jsonObject.get("expireTime"));
				}else if(jsonObject.has("shtpwd")){
					redisUtil.set("shtpwd", jsonObject.get("shtpwd"));
				}
			}
			//redis中写入标志
			redisUtil.set("cityData","exist");
		}
		logger.info("***************************************初始化操作执行完毕****************************");
	}
}
